package com.asohofrucol.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import com.asohofrucol.dao.BasicSaveDao;
import com.asohofrucol.model.intf.BasicSaveEntity;

@NoRepositoryBean
public class BasicSaveDaoImp<T, ID extends Serializable> extends
		SimpleJpaRepository<T, ID> implements BasicSaveDao<T, ID> {

	public static String LIVE_STATUS = "1";
	public static String DELETE_STATUS = "-1";

	private EntityManager entityManager;

	public BasicSaveDaoImp(JpaEntityInformation<T, ?> entityInformation,
			EntityManager entityManager) {
		super(entityInformation, entityManager);
		this.entityManager = entityManager;
	}

	public BasicSaveDaoImp(Class<T> domainClass, EntityManager entityManager) {
		super(domainClass, entityManager);

		this.entityManager = entityManager;
	}

	@Override
	public <S extends T> S saveAndLog(S entity, String user) {
		if (entity instanceof BasicSaveEntity) {
			((BasicSaveEntity) entity).setModifierUser(user);
			((BasicSaveEntity) entity).setModifiedDate(new Date());
			((BasicSaveEntity) entity).setStatus(LIVE_STATUS);
		}
		return super.save(entity);
	}

	@Override
	public <S extends T> S saveAndLogStatus(S entity, String user) {
		if (entity instanceof BasicSaveEntity) {
			((BasicSaveEntity) entity).setModifierUser(user);
			((BasicSaveEntity) entity).setModifiedDate(new Date());
		}
		return super.save(entity);
	}

	@Override
	public <S extends T> List<S> saveAndLog(List<S> entitys, String user) {
		List<S> saveEntityes = new ArrayList<S>();
		for (S entity : entitys) {
			saveEntityes.add(this.saveAndLog(entity, user));
		}
		return saveEntityes;
	}

	@Override
	public <S extends T> void deleteLogicallyAndLog(S entity, String user) {
		if (entity instanceof BasicSaveEntity) {
			((BasicSaveEntity) entity).setModifierUser(user);
			((BasicSaveEntity) entity).setModifiedDate(new Date());
			((BasicSaveEntity) entity).setStatus(DELETE_STATUS);
		}
		super.save(entity);
	}

}
